package com.asset.service.impl;

import com.asset.mapper.DepoMapper;
import com.asset.pojo.Depository;
import com.asset.service.DepositoryService;
import com.asset.util.AssetExceptionEnum;
import com.asset.util.AssetManageException;
import com.asset.util.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 11725
 */
@Slf4j
@Service
public class DepositoryServiceImpl implements DepositoryService {

    @Resource
    private DepoMapper depoMapper;

    @Override
    public PageResult<Depository> selectByPage(Integer page, Integer rows, Boolean selectAll) {
        if (selectAll == null) {
            PageHelper.startPage(page, rows);
        }

        List<Depository> depoList = depoMapper.selectAll();

        if (CollectionUtils.isEmpty(depoList)) {
            throw new RuntimeException("无匹配结果");
        }

        PageInfo<Depository> info = new PageInfo<>(depoList);

        return new PageResult<>(info.getTotal(), depoList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insert(Depository depository) {
        depository.setId(null);

        depoMapper.insert(depository);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    synchronized public void update(Depository depository) {
        if (StringUtils.isBlank(depository.getName())) {
            throw new AssetManageException(AssetExceptionEnum.DEPOSITORY_INFO_UPDATE_FAIL);
        }

        Depository record = new Depository();
        record.setId(depository.getId());
        record.setName(depository.getName());

        int row = depoMapper.updateByPrimaryKeySelective(record);
        if (row != 1) {
            throw new AssetManageException(AssetExceptionEnum.DEPOSITORY_INFO_UPDATE_FAIL);
        }
    }
}
